<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
      <button onclick="insertOneData()">存一条数据</button>
  <button onclick="insertManyData()">批量存数据</button>
  <button onclick="queryDataByKey()">查询某条数据</button>
  <button onclick="queryAllData()">查询所有数据</button>
  <button onclick="updateData()">更新数据</button>
  <button onclick="deleteData()">删除数据</button>
</body>
<script>
    const dbName = 'DB'
    const dbVersion = 2
    let db;
    function connectDB(){
        const request = window.indexedDB.open(dbName,dbVersion)

        request.onerror = function(event){
            console.log("接入数据库失败");
        }
        request.onupgradeneeded = function(event){
            console.log('数据库版本发生变化');
            db = event.target.result
            if(!db.objectStoreNames.contains('user')){
                db.createObjectStore('user', {
                   keyPath: 'id',
                   autoIncrement: true
          })
            }
        }
        request.onsuccess = function(event){
            console.log('数据库打开成功');
            db = event.target.result
        }
        }
        connectDB()
        function insertOneData(){
            // 事务
            const transaction = db.transaction(['user'],'readwrite')
            // 操作对象仓库
            const objectStore = transaction.objectStore('user')
            //写入数据
            const res = objectStore.add({
                id:1,
                name:'张三',
                age:18,
                gender:'男',
                createAt: new Date().getTime()
            })
    res.onsuccess = function (event) {
        console.log('数据写入成功')
      }
      res.onerror = function (event) {
        console.log('数据写入失败')
      }
        }
</script>
</html>